<?php
include_once 'log_text.php';

function create_message($input) {
  $markdowns = array();

  foreach ($input['groups'] as $group) {
    $markdown = '';
    // if count equals 0, font color set to info, else font color set to warning
    $font_color = 'warning';
    if ($group['count'] == 0) {
      $font_color = 'info';
    }
    $markdown .= "<font color=\"{$font_color}\">**{$group['itemTitle']}**</font>";
    $markdown .= "即将在{$group['thresholdDays']}天内到期的有";
    $markdown .= "<font color=\"{$font_color}\">**{$group['count']}人**</font>\n";
    foreach ($group['content'] as $cell) {
      $remark = '(';
      // $remark .= $cell['itemValue'] . ' ';
      $remark .= effective_days_string($cell['itemValue']);
      $remark .= ')';
      // each line of message
      $tmp = "\n> <font color=\"comment\">{$cell['clientName']} {$remark}</font>";
      // check length of $markdown if more than 4096
      if (strlen($markdown . $tmp) >= 4096) {
        array_push($markdowns, $markdown);
        $markdown = '';
      }
      $markdown .= $tmp;
    }
    array_push($markdowns, $markdown);
  }
  $notice = "**如果以上信息不正确**请**[点击此处](https://inctu.cn/cdapp/pims)**并更新相关信息，登录名为<font color=\"warning\">**旧工牌号（6位）**</font>密码默认为<font color=\"warning\">**appapp**</font>";
  array_push($markdowns, $notice);
  return $markdowns;
}

function effective_days($date_str) {
  return intval((strtotime($date_str) - time()) / 86400);
}

function effective_days_string($date_str) {
  $d = effective_days($date_str);
  if ($d > 0) {
    return "剩余{$d}天";
  }

  $d = -$d;
  return "过期{$d}天";
}

function create_message_missing($input) {
  $markdowns = [];
  $phones = '';
  $total = 0;
  foreach ($input as $group) {
    $count = $group['count'];
    if ($count > 0) {
      $total += $count;
      $title = $group['itemTitle'];
      $md = "以下<font color=\"warning\">**{$count}位**</font>同事缺失<font color=\"warning\">**{$title}**</font>信息!\n\n";
      $md .= '> <font color="comment">' . implode('、', $group['content']) . '</font>';
      $md .= "\n\n\n";
      $phones .= implode(',', $group['phones']) . ',';
      array_push($markdowns, $md);
    }
  }
  $phones = trim($phones, ',');
  $phones = array_unique(explode(',', $phones));
  $output = ['count' => $total, 'markdowns' => $markdowns, 'phones' => $phones];
  log_text(json_encode($output, JSON_UNESCAPED_UNICODE));
  return $output;
}